package com.hl.card.credit.utill;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Autowired
    RedisTemplate redisTemplate;

    //TODO 修改达到 用完释放连接
//    @Autowired
//    private JedisPool jedisPool;
//    Jedis jedis = this.jedisPool.getResource();
    public int incrExpireOrderCode(final String key, final int num, final int expire) {
        Long id= redisTemplate.opsForValue().increment(key, num);
//        Long id = jedis.incrBy(key, num);
        if ((id + 75807) >= Integer.MAX_VALUE) {
            // 避免溢出，重置，getSet命令之前允许incr插队，75807就是预留的插队空间
//            jedis.getSet(key, "0");
            redisTemplate.opsForValue().getAndSet(key,"0");
        }
        if (expire!=0) {
            expire(key, expire);
        }
        return id.intValue();
    }
    public Long expire(final String key, final int expire) {
         redisTemplate.expire(key, expire, TimeUnit.SECONDS);
         return  redisTemplate.getExpire(key);
//        return jedis.expire(key, expire);
    }

}
